package com.burgeon.backend.EnterpriseWeChat.service.Impl;

import com.burgeon.backend.EnterpriseWeChat.entity.*;
import com.burgeon.backend.EnterpriseWeChat.rest.Gtasks.*;
import com.burgeon.backend.EnterpriseWeChat.rest.action.ActionRest;
import com.burgeon.backend.EnterpriseWeChat.rest.action.Delete;
import com.burgeon.backend.EnterpriseWeChat.rest.getValueGroup;
import com.burgeon.backend.EnterpriseWeChat.service.GtasksService;
import com.burgeon.backend.EnterpriseWeChat.service.ex.UpDataException;
import com.burgeon.backend.EnterpriseWeChat.utils.TestUrlUtils;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

@Service
public class GtasksServiceImpl implements GtasksService {
    private final static Log logger = LogFactory.getLog(GtasksService.class);
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public BirthdayVip GetBirthdayVip(String token, String empId, String type, int page) {
        Info info = GetInfoByToken(token);
        GetBirthdayVip getBirthdayVip = new GetBirthdayVip(info.getUrl(),info.getAccount(),info.getPassword());
        GetBirthdayVipCount g = new GetBirthdayVipCount(info.getUrl(),info.getAccount(),info.getPassword());
        GetFeedBack getFeedBack = new GetFeedBack(info.getUrl(),info.getAccount(),info.getPassword());
        BirthdayVip birthdayVip = new BirthdayVip();
        try {
//            ArrayList<Vip> vipList = new ArrayList<>();
            ArrayList<Vip> vips = getBirthdayVip.getData(empId, type,page);
            for (Vip vip:vips) {
//                vip.setFeedBack(getFeedBack.getData(vip.getId(),"1"));//邀约反馈

                HashMap map = getFeedBack.getData(vip.getId(), "2");
                if(map != null) {
                    vip.setFeedBack(map.get("feedBack").toString());//邀约反馈
                    vip.setTarGetDate(map.get("tarGetDate").toString());
                    vip.setRecentDate(map.get("BILLDATE").toString());
                }
            }
//            for (Vip vip:vips) {
//                if("null".equals(vip.getLogoImg())){
//                    vip.setLogoImg("http://lfwd.cloudsmicro.com:8080/img/EnterpriseWeChat/vip/app.png");
//                }
//                vipList.add(vip);
//            }

            //待完成
            int waitCount = g.getData(empId,"1");
            //已完成
            int doneCount = g.getData(empId,"2");
            int count = waitCount + doneCount;
            //完成率
            DecimalFormat df = new DecimalFormat("###.##");
            String rate ;
            if(count == 0){
                rate = "0%";
            }else {
                String s=df.format(doneCount*100D/count);
//                System.out.println(s+"%");
                rate = s+"%";
            }
            birthdayVip.setWaitCount(waitCount+doneCount);
            birthdayVip.setDoneCount(doneCount);
            birthdayVip.setUndoneCount(waitCount);
            birthdayVip.setRate(rate);
            birthdayVip.setVips(vips);


        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
        return birthdayVip;
    }

    @Override
    public BirthdayVip GetDormantVip(String token, String empId, int page, String type) {
        Info info = GetInfoByToken(token);
        GetDormantVip getDormantVip = new GetDormantVip(info.getUrl(),info.getAccount(),info.getPassword());
        GetDormantVipCount g = new GetDormantVipCount(info.getUrl(),info.getAccount(),info.getPassword());
        GetFeedBack getFeedBack = new GetFeedBack(info.getUrl(),info.getAccount(),info.getPassword());
        BirthdayVip birthdayVip = new BirthdayVip();
        try {

            ArrayList<Vip>  vipList = getDormantVip.getData(empId,page,type);
            for (Vip vip:vipList) {
//                vip.setFeedBack(getFeedBack.getData(vip.getId(),"2"));//邀约反馈
                HashMap map = getFeedBack.getData(vip.getId(),"4");
                if(map != null) {
                    vip.setFeedBack(map.get("feedBack").toString());//邀约反馈
                    vip.setTarGetDate(map.get("tarGetDate").toString());
                    vip.setRecentDate(map.get("BILLDATE").toString());
                }
            }
//            for (Vip vip:vips) {
//                if("null".equals(vip.getLogoImg())){
//                    vip.setLogoImg("http://lfwd.cloudsmicro.com:8080/img/EnterpriseWeChat/vip/app.png");
//                }
//                vipList.add(vip);
//            }

            //待完成
            int waitCount = g.getData(empId,"1");
            //已完成
            int doneCount = g.getData(empId,"2");
            int count = waitCount + doneCount;
            //完成率
            DecimalFormat df = new DecimalFormat("###.##");
            String rate ;
            if(count == 0){
                rate = "0%";
            }else {
                String s=df.format(doneCount*100D/count);
//                System.out.println(s+"%");
                rate = s+"%";
            }
            birthdayVip.setWaitCount(waitCount+doneCount);
            birthdayVip.setDoneCount(doneCount);
            birthdayVip.setUndoneCount(waitCount);
            birthdayVip.setRate(rate);
            birthdayVip.setVips(vipList);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return birthdayVip;
    }

    @Override
    public Fitting GetFittingRate(String token, String empId) {
        Info info = GetInfoByToken(token);
        GetFittingRate getFittingRate = new GetFittingRate(info.getUrl(),info.getAccount(),info.getPassword());
        try {
           return getFittingRate.getData(empId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public ArrayList<FittingVip> GetFittingVip(String token, String empId, String returnState) {
        Info info = GetInfoByToken(token);
        GetFittingVip getFittingVip = new GetFittingVip(info.getUrl(),info.getAccount(),info.getPassword());
        ArrayList<FittingVip> vipList = new ArrayList<>();
        try {
            vipList =getFittingVip.getData(empId, returnState);
//            for (FittingVip vip: vips) {
//                if("null".equals(vip.getLogoImg())){
//                    vip.setLogoImg("http://lfwd.cloudsmicro.com:8080/img/EnterpriseWeChat/vip/app.png");
//                }
//                vipList.add(vip);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vipList;
    }

    /**
     * 十一单明细
     * @param token
     * @param fittingId
     * @return
     */
    @Override
    public ArrayList<FittingProduct> GetFittingItem(String token, String fittingId) {
        Info info = GetInfoByToken(token);
        GetFittingItem getFittingItem = new GetFittingItem(info.getUrl(),info.getAccount(),info.getPassword());
        ArrayList<FittingProduct> products = new ArrayList<>();
        try {
            ArrayList<FittingProduct> fittingProducts = getFittingItem.getData(fittingId);
            for (FittingProduct product:fittingProducts) {
                product.setType(token);
                String jpgUrl = "http://"+info.getUrl() + "/html/M_PRODUCT/" + product.getProductName()+".jpg";
                String pngUrl = "http://"+info.getUrl() + "/html/M_PRODUCT/" + product.getProductName()+".png";
                if(TestUrlUtils.testUrl(jpgUrl)){
                    System.err.println(jpgUrl);
                    product.setProductUrl(jpgUrl);
                }else if (TestUrlUtils.testUrl(pngUrl)){
                    System.err.println(pngUrl);
                    product.setProductUrl(pngUrl);
                }else {
                    product.setProductUrl("http://lfwd.cloudsmicro.com:8080/img/EnterpriseWeChat/product.png");
                }
                products.add(product);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return products;
    }

    /**
     * 常用语
     * @param token
     * @param empId
     * @param type
     * @return
     */
    @Override
    public ArrayList<UsefulExpressions> getVerbleTrickByGuider(String token, String empId, String type) {
        Info info = GetInfoByToken(token);
        getVerbleTrickByGuider getVerbleTrickByGuider = new getVerbleTrickByGuider(info.getUrl(),info.getAccount(),
                                    info.getPassword());
        ArrayList<UsefulExpressions> usefulExpressions = new ArrayList<>();
        try {
            usefulExpressions = getVerbleTrickByGuider.getData(empId, type);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
        return usefulExpressions;
    }

    @Override
    public void saveBirthdayInvite(String token,String cardNo, String type, String date, String inviteWay,
                                   String content, String feedback, String remark, String empId,String tarGetDate,String code) {

        Info info = GetInfoByToken(token);
        saveBirthdayInvite saveBirthdayInvite = new saveBirthdayInvite(info.getUrl(),info.getAccount(),
                info.getPassword());
        try {
            saveBirthdayInvite.getData(cardNo, type, date, inviteWay, content, feedback, remark, empId,tarGetDate,code);
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpDataException("创建失败"+e.getMessage());
        }

    }

    @Override
    public ArrayList<ValueGroup> getValueGroup(String token) {
        Info info = GetInfoByToken(token);
        getValueGroup getValueGroup = new getValueGroup(info.getUrl(),info.getAccount(),info.getPassword());
        ArrayList<ValueGroup> valueGroups = new ArrayList<>();
        try {
            valueGroups = getValueGroup.getData("RVISITLAE_TYPE");//常用语
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpDataException(e.getMessage());
        }
        return valueGroups;
    }

    @Override
    public String addPhrase(String token, String content, String type) {
        Info info = GetInfoByToken(token);
        addPhrase addPhrase = new addPhrase(info.getUrl(),info.getAccount(),info.getPassword());
        String objId = null;
        try {
            objId = addPhrase.getData(content, type);
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpDataException(e.getMessage());
        }

        return objId;
    }

    @Override
    public void modifyPhrase(String token, String id, String content, String type) {
        Info info = GetInfoByToken(token);
        modifyPhrase modifyPhrase = new modifyPhrase(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            modifyPhrase.getData(id, content, type);
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpDataException(e.getMessage());
        }

    }

    @Override
    public void deletePhrase(String token, String id) {
        Info info = GetInfoByToken(token);
        Delete delete = new Delete(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            delete.getData("APP_VIP_RVISITLAE",id);
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpDataException(e.getMessage());
        }
    }

    /**
     * 开卡任务数据
     * @param token
     * @param empId
     * @param storeId
     * @return
     */
    @Override
    public OpenCardTask GetOpenCardTaskData(String token, String empId, String storeId,String type) {
        Info info = GetInfoByToken(token);
        GetOpenCardTaskData getOpenCardTaskData = new GetOpenCardTaskData(info.getUrl(),info.getAccount(),info.getPassword());
        ActionRest actionRest = new ActionRest(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            actionRest.getData("C_STOREODMARK_GENERATE");
            SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
            Date date = new Date();
            String month = "";
            if("1".equals(type)){//本月
                month = format.format(date);
            }else if("2".equals(type)){//上月
               month = GetLastMonth(date,format);
            }

            OpenCardTask openCardTask = getOpenCardTaskData.getData(empId, storeId,month);

            return openCardTask;
        } catch (Exception e) {
//            e.printStackTrace();
            logger.info(e.getMessage());
        }
        return null;
    }

    /**
     * 开卡任务会员列表
     * @param token
     * @param type
     * @param page
     * @return
     */
    @Override
    public ArrayList<Vip>  GetOpenCardTaskVip(String token, String empId, String storeId, String type, int page) {
        Info info = GetInfoByToken(token);
        GetOpenCardTaskVip getOpenCardTaskVip = new GetOpenCardTaskVip(info.getUrl(),info.getAccount(),info.getPassword());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String startDate = "";
        String endDate = "";

        if("1".equals(type)){
            startDate = sdf.format(date)+"01";
            endDate = sdf2.format(date);
        }else if("2".equals(type)){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date); // 设置为当前时间
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月
            calendar.getTime();
            startDate = sdf.format(calendar.getTime())+"01";//上月一号
            int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            //填充 最后一天
            calendar.set(Calendar.DAY_OF_MONTH, maxDay);
            endDate = sdf2.format(calendar.getTime());
        }
        ArrayList<Vip> vipList = new ArrayList<>();
        try {
            vipList = getOpenCardTaskVip.getData(empId,storeId,startDate,endDate,page);
            return vipList;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
        return null;
    }

    private String GetLastMonth(Date date,SimpleDateFormat format){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date); // 设置为当前时间
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月
        date = calendar.getTime();
        String accDate = format.format(date);
        return accDate;
    }

    private String GetLastMonthDay(Date date,SimpleDateFormat format){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date); // 设置为当前时间
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月
        int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        //填充 最后一天
        calendar.set(Calendar.DAY_OF_MONTH, maxDay);
        date = calendar.getTime();
        String accDate = format.format(date);
        return accDate;
    }

    private Info GetInfoByToken(String token) {
        return accountMapper.GetTokenData(token);
    }
}
